package com.spring.schedule_system.controller;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spring.schedule_system.dao.Tb_classDao;
import com.spring.schedule_system.dao.TeacherDao;
import com.spring.schedule_system.entity.Tb_class;
import com.spring.schedule_system.entity.Teacher;
import com.spring.schedule_system.entity.User;
import com.spring.schedule_system.utils.JwtToken;
import com.spring.schedule_system.utils.MyUtil;
import com.spring.schedule_system.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@CrossOrigin
@Controller
@RequestMapping("/tbclass")
@Api(value = "TbClassController", description = "班级相关api")
public class TbClassController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired(required = false)
    private Tb_classDao tb_classDao;


    /**
     * 添加班级
     * @param class_code
     * @param class_name
     * @param class_profession
     * @param class_count
     * @param grade
     * @param Authorization
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     */
    @ApiOperation("添加班级")
    @PostMapping("/web/addClass")
    @ResponseBody
    public ResponseEntity addClass(@RequestParam(required = false) String class_code,
                                   @RequestParam(required = true) String class_name,
                                   @RequestParam(required = false) String class_profession,
                                   @RequestParam(required = true) String class_count,
                                   @RequestParam(required = false) String grade,
                                   @RequestHeader String Authorization) throws IOException, TokenExpiredException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User user = JwtToken.unsign(token, User.class);
        //用户角色，分学生用户和老师用户，1代表学生，2代表老师用户,默认为学生
        if (user.getUser_role()!=2){
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        QueryWrapper<Tb_class> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_code", class_code);
        Tb_class tb_class = tb_classDao.selectOne(queryWrapper);
        if (tb_class == null){
            responseEntity = ResponseEntity.ok();
            Tb_class tb_class1 = new Tb_class();
            tb_class1.setClass_code(class_code);
            tb_class1.setClass_count(class_count);
            tb_class1.setClass_name(class_name);
            tb_class1.setClass_profession(class_profession);
            tb_class1.setGrade(grade);
            tb_classDao.insert(tb_class1);
            responseEntity.putDataValue("class_id",tb_class1.getClass_id());
            responseEntity.putDataValue("class_name",tb_class1.getClass_name());
            responseEntity.putDataValue("msg","班级注册成功");
        }else {
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","班级注册失败");
        }
        return responseEntity;
    }

    /**
     * 修改班级信息
     * @param class_id
     * @param class_code
     * @param class_name
     * @param class_profession
     * @param class_count
     * @param grade
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("修改班级信息")
    @PutMapping("/web/updateClass")
    @ResponseBody
    public ResponseEntity updateClass(@RequestParam(required = true) int class_id,
                                      @RequestParam(required = false) String class_code,
                                      @RequestParam(required = false) String class_name,
                                      @RequestParam(required = false) String class_profession,
                                      @RequestParam(required = false) String class_count,
                                      @RequestParam(required = false) String grade, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else if (users.getUser_role()!=2) {
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg", "没有权限");
            return responseEntity;

        } else {
            responseEntity = ResponseEntity.ok();
            Tb_class tb_class = tb_classDao.selectById(class_id);
            tb_class.setGrade(grade);
            tb_class.setClass_profession(class_profession);
            tb_class.setClass_name(class_name);
            tb_class.setClass_count(class_count);
            tb_class.setClass_code(class_code);
            tb_classDao.updateById(tb_class);
            responseEntity.putDataValue("msg", "班级修改成功");
            return responseEntity;
        }
    }

    /**
     * 根据class_id查询班级
     * @param class_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据class_id查询班级")
    @PutMapping("/web/selectByClassId")
    @ResponseBody
    public ResponseEntity selectByClassId(@RequestParam(required = true) Integer class_id, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        }
        responseEntity=ResponseEntity.ok();
        Tb_class tb_class = tb_classDao.selectById(class_id);
        if (tb_class == null){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg", "查询的班级不存在");
            return responseEntity;
        }
        responseEntity.putDataValue("tb_class",tb_class);
        return responseEntity;

    }

    /**
     * 根据class_name查询班级
     * @param class_name
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据class_name查询班级")
    @PutMapping("/web/selectByClassName")
    @ResponseBody
    public ResponseEntity selectByClassName(@RequestParam(required = true) String class_name, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        }
        responseEntity=ResponseEntity.ok();
        QueryWrapper<Tb_class> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_name", class_name);
        Tb_class tb_class = tb_classDao.selectOne(queryWrapper);
        if (tb_class == null){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg", "查询的班级不存在");
            return responseEntity;
        }
        responseEntity.putDataValue("tb_class",tb_class);
        return responseEntity;


    }

    /**
     * 根据class_id删除班级信息
     * @param class_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据class_id删除班级信息")
    @PutMapping("/web/deleteClass")
    @ResponseBody
    public ResponseEntity deleteClass(@RequestParam(required = true) Integer class_id,@RequestHeader String Authorization)throws IOException{
        ResponseEntity responseEntity=null;
        String token=Authorization;
        if(flag=myUtil.judgeToken(token)){
            responseEntity=ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User users=JwtToken.unsign(token,User.class);
        if(users==null){
            responseEntity=ResponseEntity.notFound();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        }
        if(users.getUser_role()!=2) {
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg", "没有权限");
            return responseEntity;
        }
            Tb_class tb_class = tb_classDao.selectById(class_id);
            if(tb_class!=null) {
                tb_classDao.deleteById(class_id);
                responseEntity = ResponseEntity.ok();
                responseEntity.putDataValue("msg", "删除成功");
                return responseEntity;
            }
        return responseEntity;
    }

    /**
     * 根据class_name删除班级信息
     * @param class_name
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据class_name删除班级信息")
    @PutMapping("/web/deleteClassByClassName")
    @ResponseBody
    public ResponseEntity deleteClassByClassName(@RequestParam(required = true) String class_name,@RequestHeader String Authorization)throws IOException{
        ResponseEntity responseEntity=null;
        String token=Authorization;
        if(flag=myUtil.judgeToken(token)){
            responseEntity=ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User users=JwtToken.unsign(token,User.class);
        if(users==null){
            responseEntity=ResponseEntity.notFound();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        }
        if(users.getUser_role()!=2) {
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg", "没有权限");
            return responseEntity;
        }
        QueryWrapper<Tb_class> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_name", class_name);
        Tb_class tb_class = tb_classDao.selectOne(queryWrapper);
        if (tb_class != null) {
            QueryWrapper<Tb_class> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("class_name", class_name);
            tb_classDao.delete(queryWrapper1);
            responseEntity = ResponseEntity.ok();
            responseEntity.putDataValue("msg", "删除成功");
            return responseEntity;
        } else {
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg", "删除的课程已经不存在");
            return responseEntity;
        }

    }
    /**
     * 班级列表
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("班级列表")
    @PostMapping("/web/classList")
    @ResponseBody
    public ResponseEntity classList(@RequestHeader String Authorization,
                                       HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        QueryWrapper<Tb_class> wrapper = new QueryWrapper<>();
        List<Tb_class> list = tb_classDao.selectList(wrapper);
        if (list == null){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg", "查询的班级不存在");
            return responseData;
        }
        responseData = ResponseEntity.ok();
        responseData.putDataValue("Tb_class",list);
        responseData.putDataValue("msg","成功");
        return responseData;
    }
    /**
     * 统计班级数量
     */
    @ApiOperation("统计班级数量")
    @GetMapping("/web/count")
    @ResponseBody
    public ResponseEntity count() throws IOException {
        ResponseEntity responseData;
        int  count =tb_classDao.selectCount(null);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("count", count);
        return responseData;
    }
    /**
     * 根据class_id批量删除班级
     * @param arr
     * @param Authorization
     * @return
     */
    @ApiOperation("根据class_id批量删除班级")
    @GetMapping("/web/deleteClassListByClassId")
    @ResponseBody
    public ResponseEntity deleteClassListByClassId(@RequestParam(required = true) int[] arr,
                                            @RequestHeader String Authorization ) throws  IOException{
        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user.getUser_role()!=2){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","权限错误");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        for (int class_id : arr) {
            Tb_class tb_class = tb_classDao.selectById(class_id);
            if (tb_class != null) {
                tb_classDao.deleteById(class_id);
            }
        }
        responseData = ResponseEntity.ok();
        responseData.putDataValue("msg", "批量删除数据成功");
        return responseData;


    }

    /**
     * 根据class_name批量删除班级
     * @param arr
     * @param Authorization
     * @return
     */
    @ApiOperation("根据class_name批量删除班级")
    @GetMapping("/web/deleteClassListByClassName")
    @ResponseBody
    public ResponseEntity deleteClassListByClassName(@RequestParam(required = true) String[] arr,
                                                   @RequestHeader String Authorization ) throws  IOException{
        ResponseEntity responseData;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseData = ResponseEntity.forbidden();
            responseData.putDataValue("msg","token不存在或已过期");
            return responseData;
        }
        if (user.getUser_role()!=2){
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg","权限错误");
            responseData.putDataValue("timestamp",myUtil.getTime());
            return responseData;
        }
        for (String class_name : arr) {
            QueryWrapper<Tb_class> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_name", class_name);
            Tb_class tb_class = tb_classDao.selectOne(queryWrapper);
            if (tb_class != null) {
                QueryWrapper<Tb_class> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("class_name", class_name);
                tb_classDao.delete(queryWrapper1);
            }
        }
        responseData = ResponseEntity.ok();
        responseData.putDataValue("msg", "批量删除数据成功");
        return responseData;


    }

    /**
     * 根据class_name模糊查询班级
     * @param class_name
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据class_name模糊查询班级")
    @PutMapping("/web/selectByLikeClassName")
    @ResponseBody
    public ResponseEntity selectByLikeClassName(@RequestParam(required = true) String class_name, @RequestHeader String Authorization) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        }
        responseEntity=ResponseEntity.ok();
        QueryWrapper<Tb_class> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("class_name", class_name);
        List<Tb_class> tb_class = tb_classDao.selectList(queryWrapper);
        if (tb_class == null){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg", "查询的班级不存在");
            return responseEntity;
        }
        responseEntity.putDataValue("tb_class",tb_class);
        return responseEntity;


    }
    /**
     * 导出班级
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("导出班级")
    @PostMapping("/web/exportClass")
    @ResponseBody
    public ResponseEntity exportClass(HttpServletResponse response) throws IOException {
        ResponseEntity responseEntity;
        responseEntity=ResponseEntity.ok();
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("Sheet1");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("班级代号");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("班级名称（教学班）");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("班级专业");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("班级人数");
        cell.setCellStyle(style);
        cell = row.createCell(4);
        cell.setCellValue("年级");
        cell.setCellStyle(style);


        QueryWrapper<Tb_class> queryWrapper = new QueryWrapper<>();
        List<Tb_class> list = tb_classDao.selectList(queryWrapper);
        for (int i = 0; i < list.size() ; i++) {
            row = sheet.createRow(i+1);
            Tb_class tb_class = list.get(i);
            row.createCell(0).setCellValue(tb_class.getClass_code());
            row.createCell(1).setCellValue(tb_class.getClass_name());
            row.createCell(2).setCellValue(tb_class.getClass_profession());
            row.createCell(3).setCellValue(tb_class.getClass_count());
            row.createCell(4).setCellValue(tb_class.getGrade());
        }
        long filename = System.currentTimeMillis();
        SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
        String fileName = df.format(new Date());
        response.setContentType("application/msexcel");
        response.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");
        response.flushBuffer();
        wb.write(response.getOutputStream());
        responseEntity.putDataValue("msg","导出成功");
        return responseEntity;
    }


}
